//
//  GKHomeItemController.swift
//  MySwiftObject
//
//  Created by wangws1990 on 2020/9/9.
//  Copyright © 2020 wangws1990. All rights reserved.
//

import UIKit

class GKHomeItemController: BaseTableViewController {
    public var rankId :String?{
        didSet{
            //guard let rankId = rankId else { return }
            self.refreshData(page: 1)
        }
    }
    lazy var listData : [GKBookModel] = {
        return []
    }()
    private var bookInfo:GKHomeInfo!
    override func vtm_prepareForReuse() {
        if !self.reachable {
            self.listData.removeAll();
            self.tableView.reloadData();
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        
        self.setupEmpty(scrollView: self.tableView);
        self.setupRefresh(scrollView: self.tableView, options: .defaults);
    }
    override func refreshData(page: Int) {
        if self.rankId == nil {
            return
        }
        GKHomeNet.homeHot(rankId: self.rankId!, sucesss: { (object) in
            if page == RefreshPageStart{
                self.listData.removeAll()
            }
            if let info : GKHomeInfo = GKHomeInfo.deserialize(from: object["ranking"].rawString()){
                self.listData.append(contentsOf: info.books)
            }
            self.tableView.reloadData()
            self.endRefresh(more: false)
        }) { (error) in
            self.endRefreshFailure()
        }
    }
    override func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.listData.count
    }
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return UITableView.automaticDimension
    }
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell :GKClassifyTailCell = GKClassifyTailCell.cellForTableView(tableView: tableView, indexPath: indexPath)
        cell.model = self.listData[indexPath.row]
        return cell
    }
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated:true)
        let model:GKBookModel = self.listData[indexPath.row]
        GKJump.jumpToDetail(bookId: model.bookId ?? "")
    }
}
